#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>

struct client_info
{
    struct sockaddr_in client_addr;
    int tcp_fd;
    struct client_info *next;
    struct client_info *prev;
};

int i = 0;

struct client_info *head;
void init();
int get_listen_tcp(char *port);
void *func(void *);

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("please input port:\n");
        return -1;
    }
    int tcp_fd = get_listen_tcp("50000");
    
    int epoll_fd = epoll_create(1);
    if(epoll_fd < 0) 
    {
      perror("epoll_create fail");
      return -1;
    }

    struct epoll_event buf_event;
    buf_event.data.fd = tcp_fd;
    buf_event.events = EPOLLIN | EPOLLOUT;
    epoll_ctl(epoll_fd,EPOLL_CTL_ADD,tcp_fd,&buf_event);
    

    close(tcp_fd);
    return 0;
}

int get_listen_tcp(char *port)
{
    init();
    int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_fd < 0)
    {
        perror("socket fail");
        exit(-1);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(port));
    inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);

    int ret = bind(tcp_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    int on = 1;
    setsockopt(tcp_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    listen(tcp_fd, 5);
    return tcp_fd;
}

void init()
{
    head = malloc(sizeof(struct client_info));
    head->next = head->prev = head;
}

void *func(void *num)
{
    while (1)
    {
        printf("i %d\n", i++);
        sleep(1);
    }
}
